import { ActionSheetController, AlertController, LoadingController, ModalController, Platform } from '@ionic/angular';
import { ChangeDetectorRef, Component, Input, OnInit } from '@angular/core';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { EventService } from 'src/app/shared/service/event.service';
import { UploadImageService } from 'src/app/shared/service/uploadImageService';
import { Camera, CameraOptions } from '@ionic-native/camera/ngx';

@Component({
  selector: 'app-video-comments-foot',
  templateUrl: './video-comments-foot.component.html',
  styleUrls: ['./video-comments-foot.component.scss'],
})
export class VideoCommentsFootComponent implements OnInit {
  @Input() tagData: any = {};
  sendLabelValue: any;
  noShowFootBtn = true;
  timer: any;
  data: any;
  selectImg: any;
  maxSize = 1;
  isNative: boolean;
  currentTime: string;
  constructor(
    private actionSheetCtrl: ActionSheetController,
    private pageModalService: PageModalService,
    private appGlobalService: AppGlobalService,
    public alertController: AlertController,
    private httpService: HttpService,
    public modalController: ModalController,
    public eventService: EventService,
    private uploadImageService: UploadImageService,
    private loadingController: LoadingController,
    private ref: ChangeDetectorRef,
    private platform: Platform,
    private camera: Camera,

  ) { }

  ngOnInit() {
    this.currentTime = 'time' + Date.now();
    let that = this;
    if (this.platform.is('cordova')) {
      this.isNative = true;
    } else {
      this.isNative = false;
    }
    this.data = this.appGlobalService.videoDetailsData;
    this.tagData.valueArray = [];
    setTimeout(() => {
      document.getElementById('click-img').addEventListener('click', function(e) {
        e.preventDefault();
        let num = 0;
        let domName = 'photo-select-' + that.currentTime;
        while (num < 3) {
          console.log(num);
          num++;
          document.getElementById(domName).click();
        }
      });
    }, 200);
  }

  ionFocus(e) {
    e.stopPropagation();
  }

  ionBlur(e) {
    e.stopPropagation();
  }

  ionChange(e) {
    e.stopPropagation();
    if (this.noShowFootBtn !== false && this.sendLabelValue !== '' && this.tagData.data.footDiv.firstRowRight.firstText.img !== '') {
      setTimeout(() => {
        this.noShowFootBtn = false;
      }, 200);
    }

    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.sendLabelValue = e.detail.value;
      if (this.sendLabelValue === '' && (this.tagData.data.footDiv.firstRowRight.firstText.img === '' || this.tagData.data.footDiv.firstRowRight.firstText.img === undefined)) {
        setTimeout(() => {
          this.noShowFootBtn = true;
        }, 100);
      }
    }, 100);
  }

  async sendLabel(e, item) {
    e.stopPropagation();
    const that = this;
    if (item && item.submit && item.submit.content.label) {
      const itemContent = JSON.parse(JSON.stringify(item.submit.content));
      itemContent[itemContent.label] = this.sendLabelValue;
      itemContent[itemContent.pic_url] = this.tagData.data.footDiv.firstRowRight.firstText.img?this.tagData.data.footDiv.firstRowRight.firstText.img:'';
      const params = {
        content: itemContent,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      await this.httpService.post("application/submit", params, res => {
        if (res.success) {
          if (!that.data || that.data === undefined) {
            this.appGlobalService.reloadCurrentPage(800);
          } else {
            this.sendLabelValue = '';
            this.tagData.data.footDiv.firstRowRight.firstText.img?this.tagData.data.footDiv.firstRowRight.firstText.img = '':'';
            if (this.noShowFootBtn === false) {
              this.noShowFootBtn = true;
            }
            if (res.data && res.data.eventResult) {
              this.eventService.eventEmit.emit("videosDetails_dataItem", {id: res.data.eventResult, type: item.submit.content.type});
            }

            this.modalController.dismiss();
          }
        }
        this.appGlobalService.showToast(res.message, 1500, 'middle');
      });
    }
  }
 // App 上传文件
 async presentAction(i) {
  const that = this;
  {
    const actionSheet = await this.actionSheetCtrl.create({
      mode: 'ios',
      cssClass: 'as_padding as_common as_border_common',
      buttons: [{
        text: '相机',
        cssClass: 'as_font_bd',
        handler: () => {
          const source = this.camera.PictureSourceType.CAMERA;
          this.uploadImageService.takePicture(source, that.tagData.allowEdit, (url) => {

            if (that.tagData.valueArray.length === that.maxSize) {
              that.tagData.valueArray[that.maxSize - 1] = { path: url };
            } else {
              that.tagData.valueArray.push({ path: url });
            }

          }, null);
        }

      }, {
        text: '从手机相册选择',
        cssClass: 'as_font_color',
        handler: () => {

          // 2024.06.14 整合统一从uploadImageService处理

          this.uploadImageService.openImgPicker(
            // tslint:disable-next-line:no-shadowed-variable
            (url: any, fileName: any) => {
              that.hideLoader();
              if (that.tagData.valueArray.length === that.maxSize) {
                that.tagData.valueArray[that.maxSize - 1] = { path: url };
              } else {
                that.tagData.valueArray.push({ path: url });
              }
            },
            that.maxSize,
            1,
            null,
            {allowCropper: false }, this.ref);

        }
      },
      {
        text: '取消',
        cssClass: 'as_font_top',
        handler: () => {
          console.log('Cancel clicked');
        }
      }]
    });
    await actionSheet.present();
  }
}

  // web 上传文件
  uploadFile(event) {
    if (this.tagData.data.footDiv.firstRowRight.firstText.img && this.tagData.valueArray.length > 0) {
      return;
    }

    this.uploadFileForWeb(event);
  }

  uploadFileForWeb(event: any, fileType?: string) {

    const that = this;
    if (event.target.files && event.target.files[0]) {
      this.selectImg = event.target.files[0];
      if (['jpeg', 'png', 'gif', 'jpg', 'mp4', 'pdf'].indexOf(this.selectImg.type.split('/')[1]) > -1) {

        const reader = new FileReader();
        reader.readAsDataURL(that.selectImg);
        reader.onload = (e) => {
          const uploadData = new FormData();
          uploadData.append('file', that.selectImg);

            that.uploadImageService.uploadFileForWeb(this.selectImg, (resUrl: any) => {

              if (that.tagData.valueArray.length === that.maxSize) {
                that.tagData.valueArray[that.maxSize - 1] = { path: resUrl };
              } else {
                that.tagData.valueArray.push({ path: resUrl });
                that.tagData.data.footDiv.firstRowRight.firstText.img = resUrl;
              }
            }, that.tagData.cropperRatio);

        };
      } else {
        this.appGlobalService.showToast('格式不正确，请选择图片', 3000, 'middle');
      }
    }
  }

  delImg(e) {
    e.stopPropagation();
    this.tagData.data.footDiv.firstRowRight.firstText.img = '';
    this.tagData.valueArray = [];
  }

  showLoader() {
    this.loadingController.create({
      message: '上传文件中...'
    }).then((res) => {
      res.present();
      res.onDidDismiss().then((dis) => {
        this.ref.detectChanges(); // trigger change detection cycle
      });
    });
  }
  hideLoader() {
    const that = this;
    setTimeout(() => {
      if (that.loadingController) {
        that.loadingController.dismiss();
      }
    }, 1000);
  }
}
